﻿using dz.loger.core;
using dz.util.core;
using Dz.WorkerService.jkyschema;
using Dz.WorkerService.QueryParm;
using System.Data;

namespace Dz.WorkerService
{
    public class TaskPackage : BaseTaskItem
    {
        public TaskPackage(string name, TimeSpan interval) : base(name, interval)
        {
            docType = "packagelist";
            method = "erp-goods.goods.listgoodspackage";
            table = "dz_jky_package";
        }

 

        protected override BaseParm BuildParm(DateTime sdate, DateTime edate)
        {
            PackageListParm parm = new PackageListParm();

            return parm;
        }

        private BaseParm RebuildParm(BaseParm parm,int index)
        {
            PackageListParm rtn = parm as PackageListParm;

            rtn.pageIndex = index;

            return rtn;
        }

        protected override async Task DownLoadData(BaseParm parm)
        {
            await base.DownLoadData(parm);

            
            DataTable data = GetTable();

            processId = Guid.NewGuid().ToString();

            #region 获得循环次数
            PackageListCount count = new PackageListCount();
            int total = await count.GetCnt();

            int quotient = Math.DivRem(total, ((PackageListParm)parm).pageSize, out int remainder);

            int cnt = quotient + (remainder > 0 ? 1 : 0);
            #endregion

            try
            {
                await InsertSyncLog(processId, docType);

                for (int i = 0; i < cnt; i++)
                {
                    RebuildParm(parm, i);

                    WebResult result = await JkyUtils.Post(method, JsonUtil.Serialize(parm));

                    #region 判断http请求是否成功
                    if (!result.Sucess)
                        if (!result.Sucess)
                        {
                            throw new Exception($"下载{docType}失败：{result.Data}");
                        }
                    #endregion

                    #region 判断请求结构是否成功
                    JkyResult result1 = JsonUtil.Deserialize<JkyResult>(result.Data);
                    if (result1.code != 200)
                    {
                        throw new Exception($"下载{docType}失败：{result1.msg}");
                    }
                    #endregion

                    #region 处理请求结果
                    PackageListResult result2 = JsonUtil.Deserialize<PackageListResult>(result1.result.ToString());
                    
                    if (result2.data == null || result2.data.Count == 0) continue;
                    foreach (PackageItem item in result2.data)
                    {
                        AddData(data, item);
                    }
                    #endregion

                    
                    
                }

                await sqlUtils.Save(data, "dz_jky_package");
                await UpdateSyncLog(processId, 1);
               
 
            }
            catch (Exception ex)
            {
                await UpdateSyncLog(processId, -1, ex.Message);
                LogUtil.Instance.Error($"同步{docType}失败：{ex.Message}");
                throw new Exception(ex.Message);
            }

        }

        /// <summary>
        /// 获得数据表
        /// </summary>
        /// <returns></returns>
        private DataTable GetTable()
        {
            DataTable table = new DataTable();


            table.Columns.Add("parentcode", typeof(string));
            table.Columns.Add("parentname", typeof(string));
            table.Columns.Add("subcode", typeof(string));
            table.Columns.Add("subname", typeof(string));
            table.Columns.Add("unitName", typeof(string));
            table.Columns.Add("rate", typeof(decimal));
            table.Columns.Add("isGiveaway", typeof(int));

            return table;
        }

        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="item"></param>
        private void AddData(DataTable dt, PackageItem item)
        {
            
            if (item.goodsPackageDetail == null || item.goodsPackageDetail.Count == 0) return;
            foreach (var row in item.goodsPackageDetail)
            {
                

                DataRow dr = dt.NewRow();

                dr["parentcode"] = item.goodsNo;
                dr["parentname"] = item.goodsName;
                dr["subcode"] = row.goodsNo;
                dr["subname"] = row.goodsName;
                dr["rate"] = row.shareRatio;
                dr["isGiveaway"] = row.isGiveaway;
                dr["unitName"] = row.unitName;
                dt.Rows.Add(dr);
            }
        }

        protected override Task<DateTime> GetLastDate()
        {
            return Task.FromResult(DateTime.Now);
            
        }
    }
}
